package com.huijiet.service.impl;

import com.huijiet.base.common.CommonResult;
import com.huijiet.base.common.DataGrid;
import com.huijiet.base.common.Ref;
import com.huijiet.base.component.GlobalParam;
import com.huijiet.base.utils.ServletUtil;
import com.huijiet.base.utils.StringUtil;
import com.huijiet.base.utils.TimeUtil;
import com.huijiet.entity.News;
import com.huijiet.entity.NewsContent;
import com.huijiet.mapper.NewsContentMapper;
import com.huijiet.mapper.NewsMapper;
import com.huijiet.param.NewsParam;
import com.huijiet.service.INewsService;
import com.huijiet.vo.NewsVo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
@Transactional
public class NewsServiceImpl implements INewsService {

    @Resource
    private GlobalParam globalParam;
    @Resource
    private NewsMapper newsMapper;
    @Resource
    private NewsContentMapper newsContentMapper;


    /**后台分页查询新闻列表*/
    public CommonResult list(NewsParam.ListParam param){

        List<News> list = newsMapper.list(param.getStart(), param.getNum(),
                param.getTitle(), param.getNewsState(), param.getNewsType());

        List<NewsVo.ListVo> vos = new ArrayList<>();
        for(News news : list){
            NewsVo.ListVo vo = new NewsVo.ListVo();
            vo.setNewsId(news.getId());
            vo.setTitle(news.getTitle());
            vo.setImgUrl(news.getImgUrl());
            vo.setImgViewUrl(globalParam.getImg().getPrefix() + news.getImgUrl());
            vo.setNewsState(news.getNewsState());
            vo.setNewsType(news.getNewsType());
            vo.setCreateTime(TimeUtil.formaterYYYYMMddHHmm(news.getCreateTime()));
            if(news.getPublishTime()==null){
                news.setPublishTime(news.getCreateTime());
            }
            vo.setPublishTime(TimeUtil.formaterYYYYMMddHHmmss(news.getPublishTime()));
            vos.add(vo);
        }
        int count = newsMapper.countList(param.getTitle(), param.getNewsState(), param.getNewsType());
        DataGrid<NewsVo.ListVo> dataGrid = new DataGrid<>();
        dataGrid.setRows(vos);
        dataGrid.setTotal(count);
        return Ref.ok(dataGrid);
    }


    /**新增新闻*/
    public CommonResult add(NewsParam.AddParam param){
        //新增新闻时，新闻中的图片，如果是本地上传（不是网络图片）
        //需要去掉新闻图片的本地访问前缀
        String content = removePre(param.getContent());

        Date time = new Date();
        News news = new News();
        news.setTitle(param.getTitle());
        news.setSummary(param.getSummary());
        news.setImgUrl(param.getImgUrl());
        news.setNewsType(param.getNewsType());
        news.setNewsState(0);
        news.setCreateTime(time);

        if(StringUtil.isEmpty(param.getPublishTime())){
            news.setPublishTime(time);
        }else{
            Date date = TimeUtil.parseYYYYMMddHHmmss(param.getPublishTime());
            news.setPublishTime(date);
        }
        news.setOrderNum(news.getPublishTime().getTime());

        newsMapper.insert(news);

        NewsContent newsContent = new NewsContent();
        newsContent.setContent(content);
        newsContent.setNewsId(news.getId());
        newsContent.setCreateTime(time);
        newsContentMapper.insert(newsContent);
        return Ref.ok();
    }

    /**修改新闻*/
    public CommonResult modify(NewsParam.ModifyParam param){
        News news = newsMapper.selectById(param.getNewsId());
        if(news==null){
            return Ref.error("错误的新闻编号");
        }
        NewsContent newsContent = newsContentMapper.getByNewsId(param.getNewsId());
        if(newsContent==null){
            return Ref.error("错误的新闻编号");
        }
        if(news.getNewsState()!=0 && news.getNewsState()!=1){
            return Ref.error("只有状态为新创建或待修改的新闻才能修改");
        }

        //修改新闻时，新闻中的图片，如果是本地上传（不是网络图片）
        //需要去掉新闻图片的本地访问前缀
        String content = removePre(param.getContent());

        news.setTitle(param.getTitle());
        news.setSummary(param.getSummary());
        news.setImgUrl(param.getImgUrl());
        news.setNewsType(param.getNewsType());
        newsContent.setContent(content);


        if(StringUtil.isEmpty(param.getPublishTime())){
            news.setPublishTime(news.getCreateTime());
        }else{
            Date date = TimeUtil.parseYYYYMMddHHmmss(param.getPublishTime());
            news.setPublishTime(date);
        }
        news.setOrderNum(news.getPublishTime().getTime());

        newsMapper.updateById(news);
        newsContentMapper.updateById(newsContent);

        return Ref.ok();
    }

    /**获取新闻详情*/
    public CommonResult get(NewsParam.GetParam param){
        News news = newsMapper.selectById(param.getNewsId());
        if(news==null){
            return Ref.error("错误的新闻编号");
        }
        NewsContent newsContent = newsContentMapper.getByNewsId(param.getNewsId());
        if(newsContent==null){
            return Ref.error("错误的新闻编号");
        }

        NewsVo.GetVo vo = new NewsVo.GetVo();
        vo.setNewsId(news.getId());
        vo.setTitle(news.getTitle());
        vo.setSummary(news.getSummary());
        vo.setImgUrl(news.getImgUrl());
        vo.setImgViewUrl(globalParam.getImg().getPrefix() + news.getImgUrl());
        vo.setNewsType(news.getNewsType());
        vo.setNewsState(news.getNewsState());
        vo.setCreateTime(TimeUtil.convert(news.getCreateTime()));
        vo.setContent(addPre(newsContent.getContent()));
        return Ref.ok(vo);
    }


    /**发布新闻*/
    public CommonResult publish(NewsParam.PublishParam param){
        News news = newsMapper.selectById(param.getNewsId());
        if(news==null){
            return Ref.error("错误的新闻编号");
        }
        news.setNewsState(1);
        newsMapper.updateById(news);
        return Ref.ok();
    }

    /**取消发布*/
    public CommonResult cancel(NewsParam.CancelParam param){
        News news = newsMapper.selectById(param.getNewsId());
        if(news==null){
            return Ref.error("错误的新闻编号");
        }
        news.setNewsState(0);
        newsMapper.updateById(news);
        return Ref.ok();
    }

    /**删除新闻*/
    public CommonResult delete(NewsParam.DeleteParam param){
        News news = newsMapper.selectById(param.getNewsId());
        if(news==null){
            return Ref.error("错误的新闻编号");
        }
        newsMapper.deleteById(param.getNewsId());
        newsContentMapper.deleteByNewsId(param.getNewsId());

        return Ref.ok();
    }

    /**新闻详情*/
    public void detail(Integer newsId){
        News news = newsMapper.selectById(newsId);
        if(news==null){
            return;
        }
        NewsContent newsContent = newsContentMapper.getByNewsId(newsId);
        if(newsContent==null){
            return;
        }
        NewsVo.DetailVo vo = new NewsVo.DetailVo();
        vo.setTitle(news.getTitle());
        vo.setNewsType(news.getNewsType());
        vo.setPublishTime(TimeUtil.formaterYYYYMMdd(news.getPublishTime()));
        vo.setContent(newsContent.getContent());
        HttpServletRequest request = ServletUtil.getRequest();
        request.setAttribute("detail",vo);
    }

    /**前端获取新闻列表*/
    public CommonResult pageList(NewsParam.PageListParam param){

        List<News> list = newsMapper.list(param.getStart(), param.getNum(),
                null, 1, param.getNewsType());
        int count = newsMapper.countList(null, 1, param.getNewsType());
        List<NewsVo.PageListVo> vos = new ArrayList<>();
        for(News news : list){
            NewsVo.PageListVo vo = new NewsVo.PageListVo();
            vo.setNewsId(news.getId());
            vo.setTitle(news.getTitle());
            String summary = news.getSummary();
            if(!StringUtil.isEmpty(summary)){
                if(summary.length()>60){
                    summary = summary.substring(0, 60) + "...";
                }
                vo.setSummary(summary);
            }else{
                vo.setSummary("");
            }

            vo.setImgViewUrl(globalParam.getImg().getPrefix() + news.getImgUrl());
            vo.setPublishTime(TimeUtil.formaterYYYYMMdd(news.getPublishTime()));
            vos.add(vo);
        }
        DataGrid<NewsVo.PageListVo> dataGrid = new DataGrid<>();
        dataGrid.setRows(vos);
        dataGrid.setTotal(count);
        return Ref.ok(dataGrid);
    }


    private String removePre(String content){
        String result = content;
        if(!StringUtil.isEmpty(content)){
            Document doc = Jsoup.parse(content);
            Elements imgElements = doc.select("img");
            if(imgElements!=null){
                Iterator<Element> imgIterator = imgElements.iterator();
                while(imgIterator.hasNext()){
                    Element imgElement = imgIterator.next();
                    String src = imgElement.attr("src");
                    if(src.startsWith(globalParam.getImg().getPrefix())){
                        String url = src.replace(globalParam.getImg().getPrefix(),"");
                        imgElement.removeAttr("src");
                        imgElement.attr("src",url);
                    }
                }
            }
            String docStr = doc.html();
            docStr = docStr.replace("<html>","");
            docStr = docStr.replace("</html>","");
            docStr = docStr.replace("<head>","");
            docStr = docStr.replace("</head>","");
            docStr = docStr.replace("<body>","");
            docStr = docStr.replace("</body>","");
            result = docStr.trim();
        }
        return result;
    }

    private String addPre(String content){

        String result = content;
        if(globalParam.getImg().getDev()==0){
            return result;
        }
        if(!StringUtil.isEmpty(content)){
            Document doc = Jsoup.parse(content);
            Elements imgElements = doc.select("img");
            if(imgElements!=null){
                Iterator<Element> imgIterator = imgElements.iterator();
                while(imgIterator.hasNext()){
                    Element imgElement = imgIterator.next();
                    String src = imgElement.attr("src");
                    if(src.startsWith("/")){
                        String url = globalParam.getImg().getPrefix()+src;
                        imgElement.removeAttr("src");
                        imgElement.attr("src",url);
                    }
                }
            }
            String docStr = doc.html();
            docStr = docStr.replace("<html>","");
            docStr = docStr.replace("</html>","");
            docStr = docStr.replace("<head>","");
            docStr = docStr.replace("</head>","");
            docStr = docStr.replace("<body>","");
            docStr = docStr.replace("</body>","");
            result = docStr.trim();
        }
        return result;


    }
}
